import router from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/api/index'

const whiteList = ['/login', '/auth-redirect']

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const roles = store.state.roles
      if (roles && roles.length > 0) {
        next()
      } else {
        try {
          const { roles } = await store.dispatch('getUserInfo')
          const accessRoutes = await store.dispatch('generateRoutes', roles)
          console.log("accessRoutes", accessRoutes)
          router.addRoutes(accessRoutes)
          console.log(router)
          next({ ...to, replace: true })
        } catch (error) {
          await store.dispatch('resetToken')
          Message.error(error || 'Has Error')
          next(`/login`)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`)
    }
  }
})

router.afterEach(() => { })
